import { createStore } from "vuex";
import { login, getInfo } from "~/api/manager";
import { setToken, removeToken } from "~/composables/auth.js";

const store = createStore({
  state() {
    return {
      // 用户信息
      user: {},

      // 侧边宽度
      asideWidth: "250px",

      // 菜单数据前后端交互
      menus: [],
      ruleNames: [],
    };
  },
  mutations: {
    // 记录用户信息
    SET_USERINFO(state, user) {
      state.user = user;
    },
    // 展开/收起侧边
    handleAsideWidth(state) {
      state.asideWidth = state.asideWidth == "250px" ? "64px" : "250px";
    },
    // 菜单数据前后端交互
    SET_MENUS(state, menus) {
      state.menus = menus;
    },
    SET_RULENAMES(state, ruleNames) {
      state.ruleNames = ruleNames;
    },
  },
  actions: {
    // actions是异步的操作
    // 登录
    login({ commit }, { username, password }) {
      return new Promise((resolve, reject) => {
        login(username, password)
          .then((res) => {
            setToken(res.token);
            resolve(res);
          })
          .catch((err) => reject(err));
      });
    },
    // 获取当前登录用户信息
    getInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            // 这里的commit跟store.commit("SET_USERINFO",res)其实是一样的
            commit("SET_USERINFO", res);
            console.log("getInfo:", res);
            commit("SET_MENUS", res.menus);
            commit("SET_RULENAMES", res.ruleNames);
            resolve(res);
          })
          .catch((err) => reject(err));
      });
    },

    // 退出登录
    logout({ commit }) {
      // 移除token
      removeToken();
      // 清除当前用户状态vuex
      commit("SET_USERINFO", {});
    },
  },
});

export default store;
